package cn.yanghan.org.controller;


import cn.yanghan.org.domain.Department;
import cn.yanghan.org.query.DepartmentQuery;
import cn.yanghan.org.service.IDepartmentService;
import cn.yanghan.org.utils.AjaxResult;
import cn.yanghan.org.utils.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/department")

public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    //添加或修改
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if(department.getId()==null){

                departmentService.save(department);
            }else{
                departmentService.update(department);            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());

        }
    }

    //删除
    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());

        }
    }

    //添加或修改
    @GetMapping("/{id}")
    public Department loadById(@PathVariable("id") Long id){
      return departmentService.loadById(id);
    }

    @GetMapping
    public List<Department> loadAll(){
        return departmentService.loadAll();
    }

    @PostMapping
    public QueryResult<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.queryPage(query);
    }



    //批量删除
    //删除
    @PatchMapping
    public AjaxResult patchDel(@RequestBody Long[] ids){
        try {
            departmentService.patchDel(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());

        }
    }

    @GetMapping("/deptTree")
    public List<Department> loadDeptTree(){
        return departmentService.loadDeptTree();
    }
}
